package com.ayz.gateway.core.authorization.service;

import com.ayz.gateway.core.authorization.GatewayAuthorizingToken;
import com.ayz.gateway.core.authorization.IAuth;
import lombok.Data;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;

/**
 * @ClassName AuthService
 * @Description TODO: 提供鉴权和授权服务的类
 *                    包装了对Shiro框架的调用
 * @Author 快乐的星球
 * @Date 2023/5/11 12:11
 * @Version 1.0
 **/
@Data
public class AuthService implements IAuth {

    private Subject subject;
    /**
     * 服务端的密钥,绝对不能暴露出去
     */
    private String singingKey;
    public AuthService(String singingKey){
        //1: 获取SecurityManger 的工厂对象，此处使用 shiro.ini 配置文件初始化工厂
        Factory<SecurityManager> factory=new IniSecurityManagerFactory("classpath:shiro.ini");
        //2:获取 SecurityManger的实例
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        //3:获取一个安全框架保护的项目的抽象
        this.subject=SecurityUtils.getSubject();
        this.singingKey=singingKey;
    }
    @Override
    public boolean validate(String id, String token) {
        try {
            //鉴权
            this.subject.login(new GatewayAuthorizingToken(id,token,singingKey));
            return subject.isAuthenticated();
        }finally {
            //退出
            this.subject.logout();
        }
    }
}
